const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

exports.main = async (event, context) => {
  const { userId } = event

  // 参数验证
  if (!userId) {
    return {
      code: 400,
      data: null,
      message: '无效的用户ID参数'
    }
  }

  try {
    const db = cloud.database()
    const _ = db.command

    // 查询用户详情（包含软删除校验）
    const { data } = await db.collection('users').doc(userId)
      .field({
        nickName: true,
        real_name: true,
        age: true,
        gender: true,
        phone: true,
        address: true,
        hobby: true,
        createdTime: true,
        isDeleted: true
      })
      .get()

    // 处理查询结果
    if (!data || data.length === 0) {
      return {
        code: 404,
        data: null,
        message: '用户不存在'
      }
    }

    // 返回脱敏后的数据
    return {
      code: 200,
      data: data,
      message: 'success'
    }

  } catch (err) {
    console.error('用户详情查询失败:', err)
    return {
      code: 500,
      data: null,
      message: process.env.NODE_ENV === 'dev' 
        ? `服务端错误: ${err.message}`
        : '服务暂时不可用'
    }
  }
}